'''
resources.lib.api
~~~~~~~~~~~~~~~~~
:copyright: (c) 2013 by Enrique Martinez <enrique.espiridion@gmail.com>
'''
import os
import sys
import xbmc
import xbmcaddon
import xbmcgui
import json
import urllib
import hashlib
import urllib2
import HTMLParser
from urlparse import urljoin


h = HTMLParser.HTMLParser()

class Api():
    host = 'api.undermedia.is-by.us'
    username = None
    password = None
    proto = None
    port = None
    system_platform = None
    architecture = None
    addon = None
    
    retryMethod = None
    retryParams = None
    
    def __init__(self, username=None, password=None):
        self.addon = xbmcaddon.Addon(id='script.module.undermedia')
        print self.addon.getSetting("session_auth")
        # Define API Version
        self.api_version = '0_1_1'
        # Get the platform and architecture
        self.system_platform = 'Unknown'
        self.architecture = ''
        if sys.maxsize > 2 ** 32:
            self.architecture = '64bit'
        else:
            self.architecture = '32bit'
        if xbmc.getCondVisibility("system.platform.linux"):
            self.system_platform = 'Linux'
            if 'arm' in os.uname()[4]:
                self.architecture = 'arm'
        elif xbmc.getCondVisibility("system.platform.xbox"):
            self.system_platform = 'Xbox'
            self.architecture = ''
        elif xbmc.getCondVisibility("system.platform.windows"):
            self.system_platform = 'Windows'
        elif xbmc.getCondVisibility("system.platform.osx"):
            self.system_platform = 'Darwin'
            if 'RELEASE_ARM' in os.uname()[3]:
                self.architecture = 'ios'
            else:
                self.architecture = 'osx'
        elif xbmc.getCondVisibility("system.platform.ios"):
            self.system_platform = 'Darwin'
            self.architecture = 'ios'
        elif xbmc.getCondVisibility("system.platform.android"):
            self.system_platform = 'Android'
            self.architecture = ''
        if self.system_platform == 'Windows':
            self.proto = 'http'
            self.port = '2897'
        else:
            if self.architecture == 'arm':
                self.proto = 'http'
                self.port = '2897'
            else:
                self.proto = 'https'
                self.port = '443'
            
        self.username = username
        md5 = hashlib.md5()
        md5.update(password)
        self.password = md5.hexdigest();
        if( not self.addon.getSetting("session_auth") ):
            self.login()
        
    def login(self):
        return self.request('login')
        
    def login_nonce(self, nonce_auth ):
        md5nonce = hashlib.md5()
        md5nonce.update(nonce_auth + self.username + self.password)
        return self.request('request_session', { 'nonce_auth' : md5nonce.hexdigest() })
        
    def get_categories(self):
        '''Returns the list of available categories'''
        # The JSON api returns a few categories that are only relevant to the
        # website and don't contain videos, so we'll ignore them
        resp = self.request('categories')
        return [{
                 'kreq': cat['id'],
                 'label': cat['name'],
                 'thumbnail': cat['thumb']
                } for cat in resp['categories']]
        
    def get_category_content(self, rkey):
        resp = self.request('ccontent', {'rkey' : rkey})
        return [{
                 'kreq': cat['id'],
                 'label': cat['name'],
                 'thumbnail': cat['thumb']
                } for cat in resp['category_items']]
        
    def get_item_content(self, rkey):
        resp = self.request('icontent', {'rkey' : rkey})
        return [{
                 'kreq': r['id'],
                 'label': r['name'],
                 'thumbnail': r['thumb'],
                 'type': r['type'],
                 'is_playable': True,
                 'info_type': r['info_type'] if r['info_type'] else '',
                 'play_type': r['play_type'] if r['play_type'] else '',
                 'plot' : r['plot'] if r['plot'] else '',
                 'duration' : r['duration'] if r['duration'] else 0,
                 'size' : r['size'] if r['size'] else 0,
                 'properties' : r['properties']
                } for r in resp['items']]
    
    def get_stream_content(self, rkey):
        return self.request('scontent', {'rkey' : rkey})
        
    def unescape(self, text):
        '''Unescapes HTML entities in the provided text'''
        return h.unescape(text)


    def request(self, method, params=None):
        '''Returns a decoded JSON response for the given url'''
        # Their API is returning some weird characters at the beginning of the
        # response which breaks the JSON parser, so we need to strip them first.
        
                
        if( method == 'login' ):
            url = self.proto + '://' + self.host + ':' + self.port + '/xbmc/' + self.api_version + '/' + method + '/?' + urllib.urlencode({'user' : self.username, 'secret' : self.password })
        elif( method == 'request_session' ):
            url = self.proto + '://' + self.host + ':' + self.port + '/xbmc/' + self.api_version + '/' + method + '/?' + urllib.urlencode(params) + '&' + urllib.urlencode({'user' : self.username, 'secret' : self.password })
        else:
            if( self.retryMethod == method ):
                self.retryMethod = ''
                self.retryParams = ''
                
            if( not self.addon.getSetting("session_auth") ):
                self.login()
            else:
                if params:
                    url = self.proto + '://' + self.host + ':' + self.port + '/xbmc/' + self.api_version + '/' + self.addon.getSetting("session_auth") + '/' + method + '/?' + urllib.urlencode(params) + '&' + urllib.urlencode({'user' : self.username, 'secret' : self.password })
                else:
                    url = self.proto + '://' + self.host + ':' + self.port + '/xbmc/' + self.api_version + '/' + self.addon.getSetting("session_auth") + '/' + method + '/?' + urllib.urlencode({'user' : self.username, 'secret' : self.password })
        
        print url
        conn = urllib2.urlopen(url)
        raw = conn.read()
        conn.close()
        start, end = raw.find('{'), raw.rfind('}') + 1
        jsondata = json.loads(raw[start:end])
        print jsondata
        if jsondata['request']['result'] == 'ok':
            if( not "session_auth" in jsondata['request'] ):
                xbmcgui.Dialog().ok("Addon Error", "Please call for assistance")
                return false
            
            self.addon.setSetting("session_auth", jsondata['request']['session_auth']) 
            if( self.retryMethod ):
                self.request(self.retryMethod, self.retryParams)
            else:
                return jsondata['request']['data']
            
        elif jsondata['request']['result'] == 'nonce_auth':
            self.login_nonce(jsondata['request']['data'])
            
        elif jsondata['request']['result'] == 'session_expired':
            self.retryMethod = method
            self.retryParams = params
            self.addon.setSetting("session_auth", '')
            self.login()
            
        elif jsondata['request']['result'] == 'expiredaccount':
            xbmcgui.Dialog().ok("Expired Account", "Your account its not valid anymore")
            return false
        elif jsondata['request']['result'] == 'badcredentials':
            xbmcgui.Dialog().ok("Invalid login", "Wrong username or password")
            return false
        else:
            xbmcgui.Dialog().ok("Addon Error", "Please call for assistance")
            return false
        
